package com.atguigu.vod.service.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;

import com.aliyun.sdk.service.vod20170321.models.*;
import com.aliyun.sdk.service.vod20170321.*;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.util.VodProperties;
import com.atguigu.vod.util.VodRemoveVideoUtil;
import com.google.gson.Gson;

import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @descriptions:
 * @author: pandengZhu
 * @date: 2024/3/27 0:26
 * @version: 1.0
 */
@Service
public class VodServiceImpl implements VodService {


    /**
     * 上传视频
     *
     * @param file 视频文件
     * @return 视频id
     */
    @Override
    public String uploadAlyVideo(MultipartFile file) {

        try {
            //上传文件的原始名称
            String fileName = file.getOriginalFilename();

            //上传文件之后显示名称
            String title = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));

            InputStream inputStream = file.getInputStream();

            UploadStreamRequest request = new UploadStreamRequest(VodProperties.ACCESS_KEY_ID, VodProperties.ACCESS_KEY_SECRET, title, fileName, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
            String videoId=null;
            if (response.isSuccess()) {
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                 videoId = response.getVideoId();

            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                 videoId = response.getVideoId();
                System.out.print("VideoId=" + response.getVideoId() + "\n");
                System.out.print("ErrorCode=" + response.getCode() + "\n");
                System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            }
            return videoId;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 根据视频video_source_id删除视频
     *
     * @param id
     */
    @Override
    public void removeVideo(String id) {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(VodProperties.ACCESS_KEY_ID)
                .accessKeySecret(VodProperties.ACCESS_KEY_SECRET)
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-shanghai") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("vod.cn-shanghai.aliyuncs.com")
                )
                .build();

        DeleteVideoRequest deleteVideoRequest = DeleteVideoRequest.builder()
                .videoIds(id)
                .build();

        CompletableFuture<DeleteVideoResponse> response = client.deleteVideo(deleteVideoRequest);
        DeleteVideoResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(new Gson().toJson(resp));
        client.close();
    }

    /**
     * 批量删除视频
     *
     * @param videoIdList
     */
    @Override
    public void removeMoreAlyVideo(List videoIdList) {
        VodRemoveVideoUtil.removeVideoList(videoIdList);
    }

    /**
     * 获取视频播放凭证
     *
     * @param id
     * @return
     */
    @Override
    public String getVideoPlayAuth(String id) {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(VodProperties.ACCESS_KEY_ID)
                .accessKeySecret(VodProperties.ACCESS_KEY_SECRET)
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-shanghai") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/vod
                                .setEndpointOverride("vod.cn-shanghai.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        GetVideoPlayAuthRequest getVideoPlayAuthRequest = GetVideoPlayAuthRequest.builder()
                .videoId(id)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<GetVideoPlayAuthResponse> response = client.getVideoPlayAuth(getVideoPlayAuthRequest);
        // Synchronously get the return value of the API request
        GetVideoPlayAuthResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(new Gson().toJson(resp));
        String playAuth = resp.getBody().getPlayAuth();
        client.close();
        return playAuth;
    }
}




